﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using deviceManage.Models;
using deviceManage.vo;
using deviceManage.Filters;
using deviceManage.VO;
using Newtonsoft.Json;

namespace deviceManage.Controllers
{
    /// <summary>
    /// 角色管理
    /// </summary>
    [CheckLoginAttribute]
    public class RoleController : Controller
    {
        private readonly DeviceCtx _context;

        public RoleController(DeviceCtx context)
        {
            _context = context;
        }

        //列表主页
        public IActionResult Index()
        {
            return View();
        }

        //ajax 获取分页数据
        public AjaxResult list(int page, int limit, String name)
        {

            AjaxResult r = new AjaxResult();
            r.Count = _context.Role.Count();
            r.Code = 0;
            r.Data = _context.Role.Where(p=>((name == null) || p.RoleName.Contains(name)))                
                .Skip((page - 1) * limit).Take(limit)
                .ToList();

            return r;
        }


        /// <summary>
        /// 进入创建页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            return View();
        }


        [HttpPost]
        public AjaxResult doCreate(string name, string nodes,string view_flag)
        {
            var count = _context.Role.Where(p => p.RoleName == name).Count();
            if (count > 0)
            {
                return AjaxResult.GetError("角色名称已存在，请检查后重新添加");
            }
            Role role = new Role();
            role.RoleName = name;
            if (string.IsNullOrEmpty(view_flag))
            {
                role.view_flag = null;
            }
            else
            {
                role.view_flag = 1;
            }
            _context.Add(role);
            _context.SaveChanges();
                                   

            var arrdata = Newtonsoft.Json.Linq.JArray.Parse(nodes);
            foreach(var item in arrdata)
            {
                string id = item["nodeId"].ToString();
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.RoleId = role.Id;
                roleMenu.MenId = id;
                _context.RoleMenu.Add(roleMenu);
            }

            _context.SaveChanges();


            return AjaxResult.GetOK("操作成功！");
        }

        /// <summary>
        /// 进入编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(string id)
        {
            var role = await _context.Role.FindAsync(id);
            return View(role);
        }

        /// <summary>
        /// 提交编辑
        /// </summary>        
        /// <returns></returns>
        [HttpPost]
        public AjaxResult DoEdit(string id, string name,string nodes, string view_flag)
        {
            Role role = this._context.Role.Single(p => p.Id == id);

            var count = this._context.Role.Where(p => p.RoleName == name && p.Id != id).Count();
            if (count > 0)
            {
                return AjaxResult.GetError("角色名称已存在，请检查后重新添加");
            }
            
            role.RoleName = name;
            if (string.IsNullOrEmpty(view_flag))
            {
                role.view_flag = null;
            }
            else
            {
                role.view_flag = 1;
            }
            this._context.Role.Update(role);
            this._context.SaveChanges(); //保存

            //删除旧的授权
            var roleMenuList = this._context.RoleMenu.Where(p => p.RoleId == id).ToList();
            foreach (RoleMenu m in roleMenuList)
            {
                this._context.Remove(m);
            }


            //保存新的授权
            var arrdata = Newtonsoft.Json.Linq.JArray.Parse(nodes);
            foreach (var item in arrdata)
            {
                string menuId = item["nodeId"].ToString();
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.RoleId = role.Id;
                roleMenu.MenId = menuId;
                _context.RoleMenu.Add(roleMenu);
            }

            _context.SaveChanges();

            return AjaxResult.GetOK("保存成功！");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult Delete(string id)
        {
            if ("06801c62-d538-4a9a-91e5-7eb4670a9973".Equals(id))
            {
                return AjaxResult.GetError("管理员角色不能被删除");
            }

            AjaxResult result = new AjaxResult();
            if (id == null) return AjaxResult.GetError("删除失败！");

            result.Code = 1;
            var role = _context.Role.FirstOrDefault(m => m.Id == id);
            if (role == null) return AjaxResult.GetError("未找到数据");


            //判断当前角色下是否存在用户
            var exist = this._context.RoleUser.Any(p => p.RoleId == id);
            if (exist)
            {
                return AjaxResult.GetError("当前角色下存在用户信息，不能进行删除");
            }

            //首先角色菜单删除
            var roleMenuList =  this._context.RoleMenu.Where(p => p.RoleId == id).ToList();
            foreach(RoleMenu m in roleMenuList)
            {
                this._context.Remove(m);
            }

            //然后删除角色
            this._context.Remove(role);

            _context.SaveChanges();
            return AjaxResult.GetOK("删除成功");
        }

        

        public TreeModel GetMenuTree()
        {
            TreeModel model = new TreeModel();

            //获取菜单列表
            var topList = this._context.Menu
                .Where(p=>p.Level ==1)
                .OrderBy(p => p.Level)
                .OrderBy(p => p.sort_order)
                .ToList();

            foreach(var m in topList)
            {
                TreeNode parent = new TreeNode(m.Id, m.Name, m.ParentId, false);
                model.data.Add(parent);

                //获取子节点
                var subList = this._context.Menu
                .Where(p => p.Level == 2 && p.ParentId == m.Id)                
                .OrderBy(p => p.sort_order)
                .ToList();
                foreach (var sub in subList)
                {
                    parent.children.Add(new TreeNode(sub.Id,sub.Name,sub.ParentId,false));
                }

            }

            return model;

        }

        public TreeModel GetRoleMenuTree(string id)
        {
            //获取授权列表
            var authList = this._context.RoleMenu.Where(p => p.RoleId == id).ToList();

            TreeModel model = new TreeModel();

            //获取菜单列表
            var topList = this._context.Menu
                .Where(p => p.Level == 1)
                .OrderBy(p => p.Level)
                .OrderBy(p => p.sort_order)
                .ToList();

            foreach (var m in topList)
            {
                var topAuth = isMenuAuth(m.Id, authList);
                TreeNode parent = new TreeNode(m.Id, m.Name, m.ParentId, topAuth);
                model.data.Add(parent);

                //获取子节点
                var subList = this._context.Menu
                .Where(p => p.Level == 2 && p.ParentId == m.Id)
                .OrderBy(p => p.sort_order)
                .ToList();
                foreach (var sub in subList)
                {
                    var auth = isMenuAuth(sub.Id, authList);
                    parent.children.Add(new TreeNode(sub.Id, sub.Name, sub.ParentId, auth));
                }

            }

            return model;
        }

        private Boolean isMenuAuth(string menuId,List<RoleMenu> list)
        {
            foreach(var roleMenu in list)
            {
                if (roleMenu.MenId.Equals(menuId))
                {
                    return true;
                }
            }
            return false;
        }

    }
}
